package com.retail.bbq.cola.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.retail.bbq.cola.constant.ColaHttpUrlConfig;
import com.retail.bbq.cola.enums.ApiForwardRedisEnum;
import com.retail.bbq.cola.service.ApiForwardService;
import com.retail.bbq.cola.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ApiForwardServiceImpl implements ApiForwardService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ColaHttpUrlConfig colaHttpUrlConfig;

    @Override
    public ResultVO<?> forward(String subPath, HttpMethod method, MultiValueMap<String, ?> params, HttpHeaders headers, String body) {
        // 1. 构建目标URL
        String targetUrl = colaHttpUrlConfig.getForwardTargetUrl(subPath);
        log.info("转发COLA URL PATH:{}", targetUrl);
        ApiForwardRedisEnum matchPathEnumByPath = ApiForwardRedisEnum.getMatchPathEnumByPath(subPath);
        String redisKey = null;
        Pattern pattern = null;
        Matcher matcher = null;
        if(Objects.nonNull(matchPathEnumByPath)){
            switch (matchPathEnumByPath) {
                //活动信息缓存
                case LOTTERY_CACHE_INFO:
                    pattern = Pattern.compile(matchPathEnumByPath.getPath()
                            .replace("{setupId}", "(?<setupId>[^/]+)")
                            .replace("/", "\\/"));
                    matcher = pattern.matcher(subPath);
                    redisKey = String.format(matchPathEnumByPath.getApiRedisKey(), matcher.group("setupId"));
                    break;
                //订单信息缓存
                case ORDER_CACHE_INFO:
                    pattern = Pattern.compile(matchPathEnumByPath.getPath()
                            .replace("{buCode}", "(?<buCode>[^/]+)")
                            .replace("{setupId}", "(?<setupId>[^/]+)")
                            .replace("/", "\\/"));
                    matcher = pattern.matcher(subPath);
                    redisKey = String.format(matchPathEnumByPath.getApiRedisKey(), matcher.group("buCode"), matcher.group("setupId"));
                    break;
                default:
                    break;
            }
            Object cacheLotteryInfo = redisTemplate.opsForValue().get(redisKey);
            if(Objects.nonNull(cacheLotteryInfo)){
                log.info("{}获取缓存,根据缓存key{}获取获取用户信息:{}", matchPathEnumByPath.getName(),redisKey, cacheLotteryInfo);
                return ResultVO.succ(cacheLotteryInfo.toString());
            }
        }
        // 2. 参数处理(可根据需要修改)
        MultiValueMap<String, ?> processedParams = processParams(subPath, params);
        HttpHeaders processedHeaders = processHeaders(headers);
        // 3. 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(body, processedHeaders);
        // 4. 执行请求
        ResponseEntity<String> response = restTemplate.exchange(
                targetUrl,
                method,
                requestEntity,
                String.class,
                processedParams);
        // 5. 返回响应
        // TODO 判断条件调整
        if(response.getStatusCode() == HttpStatus.OK &&  response.getBody() != null){
            if(StringUtils.isNotBlank(redisKey)){
                redisTemplate.opsForValue().set(redisKey, response.getBody(), 30, TimeUnit.MINUTES);
            }
            return ResultVO.succ(response.getBody());
        }else{
            return ResultVO.error(Integer.valueOf(response.getStatusCode().toString()), response.getBody().toString());
        }
    }


    private MultiValueMap<String, ?> processParams(String subPath, MultiValueMap<String, ?> params) {
        // 可以根据接口名，添加参数处理逻辑
        if(subPath == ""){
            //TODO
        }
        return params;
    }

    private HttpHeaders processHeaders(HttpHeaders headers) {
        // 可以添加请求头处理逻辑
        HttpHeaders newHeaders = new HttpHeaders();
        headers.forEach((key, values) -> {
            if (!key.equalsIgnoreCase("host")) { // 移除host头
                newHeaders.addAll(key, values);
            }
        });
        // 可以添加固定头
        // newHeaders.add("X-Forwarded-By", "gateway-service");
        return newHeaders;
    }

}
